package com.wjy.game.viewer;

import java.awt.*;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wjy
 * @date 2025/5/20 11:06
 * @description 主视图
 */
@Data
@Slf4j
public abstract class Viewer extends JFrame {

    private int width = 770;

    private int height = 530;

    public Viewer() throws HeadlessException {
        setTitle("五子棋");
        loadIcon();

        setResizable(false);
        setLayout(getLayoutManager());
        position();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void initUI() {
        repaintUI();
        setVisible(true);
        actions();
    }

    protected abstract void repaintUI();

    protected abstract void actions();

    /**
     * 添加按钮监听器
     * @param btn
     * @param listener
     */
    protected void addBtnListener(AbstractButton btn, ActionListener listener) {
        if (btn != null && btn.getActionListeners().length == 0) {
            btn.addActionListener(listener);
        }
    }

    protected LayoutManager getLayoutManager() {
        return null;
    }

    protected Dimension dimension() {
        return Toolkit.getDefaultToolkit().getScreenSize();
    }

    private void position() {
        int width = getWidth();
        int height = getHeight();
        location(width, height);
        setSize(width, height);
    }

    protected void location(int width, int height) {
        Dimension dimension = dimension();
        double ScreenWidth = dimension.getWidth();
        double ScreenHeight = dimension.getHeight();
        setLocation((int)(ScreenWidth - width) / 2, (int)(ScreenHeight - height) / 2);
    }

    private void loadIcon() {
        // 设置窗口图标
        try {
            Image icon = ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource("img.png")));
            setIconImage(icon);
        } catch (IOException e) {
            log.error("无法加载图标文件: {}", e.getMessage());
        }
    }

}
